package cn.kgc.springbootdemo.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Objects;

/**
 * <h3>springbootdemo</h3>
 * <p>分页工具</p>
 *
 * @author : DongZeJian
 * @date : 2020-05-09 13:33
 **/
@Data
@ApiModel("分页类")
public class BasePage implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * mongo创建查询时，需要忽略的字段
     */
    public static final String[] MONGO_IGNORE_FIELDS = {"size", "current"};

    /**
     * 分页大小
     */
    @ApiModelProperty(value = "分页大小", example = "10", required = true, position = 1)
    @NotNull(message = "分页大小不能为空！")
    protected Long size;

    /**
     * 当前分页
     */
    @ApiModelProperty(value = "当前页码", example = "1", required = true, position = 2)
    @NotNull(message = "当前页码不能为空！")
    protected Long current;

    /**
     * 区域id
     */
    @ApiModelProperty(value = "区域id", example = "2019123456789")
    protected String gctId;

    /**
     * 转换为page对象，注意，当size>20时，会处理成20
     *
     * @param <T>
     * @return
     */
    public <T> Page toPage() {
        Page<T> page = new Page<>();
        if (Objects.nonNull(this.size) && this.size > 20) {
            page.setCurrent(20);
        } else {
            page.setSize(this.size);
        }
        page.setCurrent(this.current);
        return page;
    }

    /**
     * 转为Pageable
     *
     * @return Pageable
     */
    public Pageable toPageable() {
        return PageRequest.of(current.intValue() - 1, size.intValue());
    }


}
